﻿using System;
using System.Configuration;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using Titan.Core;
using Titan.Core.Cryptography;
using Titan.WinFormSys.Entity;

namespace Titan.WinFormSys
{
    /// <summary>
    /// 修改密码
    /// </summary>
    public sealed partial class FrmModifyPwd : Form
    {
        /// <summary>
        /// 修改密码
        /// </summary>
        public FrmModifyPwd()
        {
            InitializeComponent();
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            DoUpdatePwd();
        }

        private void DoUpdatePwd()
        {
            var strUserId = FrmBase.UserInfo.UserId;
            var strOldPwd = txt_OldPwd.Text.Trim();
            var strNewPwd = txt_NewPwd.Text.Trim();
            var strOkPwd = txt_OkPwd.Text.Trim();

            if (strNewPwd != strOkPwd)
            {
                MessageBox.Show(@"新密码与确认密码不一致!");
                return;
            }

            DoModifyPwd(strUserId,strOldPwd,strNewPwd);

        }

        private static void DoModifyPwd(string  strUserId,string strOldPwd,string strNewPwd)
        {
            var url = ConfigurationManager.AppSettings["Url"];
            var modifyRequestJson = new ModifyPwdReqEntity.ModifyPwdRequestJson
            {
                StrUserId = strUserId,
                StrNewPwd = BitConverter.ToString(SHA1.Encrypt(Encoding.UTF8.GetBytes(strNewPwd))).Replace("-", "").ToLower(),
                StrOldPwd = BitConverter.ToString(SHA1.Encrypt(Encoding.UTF8.GetBytes(strOldPwd))).Replace("-", "").ToLower(),
                Sql = "PCK_UserLogin.MODIFYPWD" 
            
            };
            var reqJsonContent = JsonConvert.SerializeObject(modifyRequestJson);
            var dasClientRespons = DasClinet.SendPost(url + "/Login/Modify.do", 30*1000, true, FrmBase.UserInfo.UserName,strOldPwd, reqJsonContent);
            var jsonRsp =JsonConvert.DeserializeObject<ModifyPwdReqEntity.ModifyPwdResponseJson>(dasClientRespons.ResponseContentPlain);
            if (dasClientRespons.IsSuccess && dasClientRespons.StatusCode == 1 && jsonRsp.Result == 1)
            {
                MessageBox.Show(@"修改密码成功，请重新登陆!");
                return;
            }
            MessageBox.Show(@"修改密码失败!");
        }


        private void btn_Cancle_Click(object sender, EventArgs e)
        {
            Close();
            Dispose();
        }
    }
}
